#coding:utf-8
'''
create on 2017-05-31

@author: sandy
'''

import logging
from twisted.internet import reactor, defer
from twisted.web.client import Agent, readBody
from twisted.web.http_headers import Headers
from twisted.web.iweb import IBodyProducer
from zope.interface import implements
import json
import XYConfig
import ClientFactory

class StringProducer(object):
    implements(IBodyProducer)
 
    def __init__(self, body):
        self.body = body
        self.length = len(body)
 
    def startProducing(self, consumer):
        consumer.write(self.body)
        return defer.succeed(None)
 
    def pauseProducing(self):
        pass
 
    def stopProducing(self):
        pass


class XYGate(object):
    def __init__(self):
        pass
    def cbRequest(self, response, cid, xyuid, xytoken):
        logging.debug(u"XY response.code=%d cid=%d", response.code, cid)
        d = readBody(response)
        d.addCallback(self.cbBody, cid, xyuid, xytoken)
        return d
    def cbBody(self, body, cid, xyuid, xytoken):
        body = body.decode(XYConfig.ENCODING)
        logging.info(u"XY cid=%d, xyuid=%s body=%s",cid,xyuid,body)
        c = ClientFactory.instance.getProtocol(cid) 
        jf = json.loads(body)
        ret = jf.get(u'ret')
        if ret!=0:
            logging.warn(u'XY login error ret=%d error=%s',ret,jf.get(u'error'))
        logging.debug(u"######### End validate XY platform #########")
    def send(self,cid,xyuid,xytoken):
        logging.debug(u"######### Start validate XY platform #########")
        logging.debug(u"XY send cid=%d, xyuid=%s",cid, xyuid)
        data = u'uid=%s&appid=%s&token=%s' % (xyuid,XYConfig.APP_ID,xytoken)
        logging.debug(u'data=%s', data)
        data = data.encode(XYConfig.ENCODING)
        agent = Agent(reactor)
        d = agent.request("POST",XYConfig.AUTH_URL.encode(XYConfig.ENCODING),Headers({'Content-Type':['application/x-www-form-urlencoded']}),StringProducer(data) if data else None)
        d.addCallback(self.cbRequest, cid, xyuid, xytoken)


instance = XYGate()
if __name__ == '__main__':
    pass
